package ResImpl;
import java.io.Serializable;
import java.util.LinkedList;


public class Transaction implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5351139354527717554L;
	private int xId;
	private LinkedList<RecordState> operations;
	private boolean committed = false;
	private boolean aborted = false;
	private boolean voted = false;
	private long startTime;
	private boolean[] activeRMs = {false,false,false};
	
	
	public Transaction(int id){
		xId = id;
		operations = new LinkedList<RecordState>();
		startTime = System.currentTimeMillis();
	}
	
	public int getId(){
		return xId;
	}
	
	public void addRM(int rm){
		switch(rm){
		case MiddlewareServer.CARS:
			activeRMs[0] = true;
			break;
		case MiddlewareServer.FLIGHTS:
			activeRMs[1] = true;
			break;
		case MiddlewareServer.HOTELS:
			activeRMs[2] = true;
			break;
		default:
			break;
		}
	}
	
	public boolean usesCars(){
		return activeRMs[0];
	}
	
	public boolean usesFlights(){
		return activeRMs[1];
	}
	
	public boolean usesHotels(){
		return activeRMs[2];
	}
	
	public boolean hasBeenWritten(String key){
		for(int i = 0;i<operations.size();i++){
			if(operations.get(i).getKey().equals(key)){
				return true;
			}
		}
		return false;
	}
	
	public void addWrite(int type, String key, Object[] values){
		
		if(!hasBeenWritten(key)){
			operations.add(new RecordState(type,key,values));
		}			

	}
	
	public LinkedList<RecordState> getOperations(int id){
		return operations;
	}
	
	public boolean isCommited(){
		return committed;
	}
	
	public boolean isAborted(){
		return aborted;
	}
	
	public void commit(){
		committed = true;
	}
	
	public void abort(){
		aborted = true;
	}
	
	public int getElapsedTime(){
		long currentTime = System.currentTimeMillis();
		long elapsedTime = currentTime - startTime;
		elapsedTime = elapsedTime/1000;
		return (int)elapsedTime;
	}
	
	public void resetTTL(){
		startTime = System.currentTimeMillis();
	}
	
	public void setVoted(){
		voted = true;
	}
	
	public boolean hasVoted(){
		return voted;
	}
	
}
